<?php namespace system\model;
/**
 * 刘超群
 * 登陆 注册
 *
 * 2016年10月12日21:35:43
 */


use hdphp\model\Model;

class Login extends Model{

	//数据表
	protected $table = "login";

	//完整表名
	protected $full = false;

	//自动验证
	protected $validate=[
		//['字段名','验证方法','提示信息',验证条件,验证时间]
		['user_name','regexp:/^[a-zA-Z0-9_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]+$/','账号必须为两位以上的字母,数字,或者下划线',3,3],
		['password','required','请输入密码',3,3],
		['code','required','请输入验证码',3,3]
	];

	//自动完成regexp:
	protected $auto=[
		//['字段名','处理方法','方法类型',验证条件,验证时机]
	];

	//自动过滤
    protected $filter=[
        //[表单字段名,过滤条件,处理时间]
    ];

	//时间操作,需要表中存在created_at,updated_at字段
	protected $timestamps=false;


	//禁止插入的字段
	protected $denyInsertFields = [];

	//禁止更新的字段
	protected $denyUpdateFields = [];

	//前置方法 比如: _before_add 为添加前执行的方法
	protected function _before_add(){}
	protected function _before_delete(){}
	protected function _before_save(&$data){}

	protected function _after_add(){}
	protected function _after_delete(){}
	protected function _after_save(){}
	public function register(){
		if(!$this->create()) return false;
		if (strtoupper($_POST[code])!=$_SESSION['code']){
			$this->error='验证码错误';
			return false;
		}
		$user_name =$this->lists('user_name');
		foreach ($user_name as $k =>$v){
			if ($_POST['user_name'] ==$v){
				$this->error = '账号已存在';
				return false;
			}
		}
		$regexp='/^[\w\_]{6,20}$/u';
		if(!preg_match($regexp,$_POST['password'])){
			$this->error ='密码必须为6—20位,由字母、数字组成';
			return false;
		}
		$this->data['password']=Crypt::encrypt($_POST['password']);
//		p($this->data);exit;
		$this->add();
		return true;
	}
	public function login(){
		if(!$this->create()) return false;
		if (strtoupper($_POST[code])!=$_SESSION['code']){
			$this->error='验证码错误';
			return false;
		}
		if(!$data = $this->where('user_name',$_POST['user_name'])->where('password',Crypt::encrypt($_POST['password']))->first()){
			$this->error = '用户名密码错误';
			return false;
		}
		$_SESSION['admin']['logid'] = $data['uid'];
		$_SESSION['admin']['username'] = $data['user_name'];
		return true;
	}
}